package com.liupf.controller;

import java.util.List;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.liupf.common.utils.Constants;
import com.liupf.domain.TelPriceRule;

public class PriceRuleController extends Controller{

	public void index(){
		String company=(String) getSession().getAttribute("company");
		String userRole = (String)getSession().getAttribute("userRole");
		
		StringBuffer sql = new StringBuffer("select * from tel_price_rule where 1=1 ");
		if(Constants.ROLE_BRAND_MANAGER.equals(userRole) || Constants.ROLE_MIDDLE_MANAGER.equals(userRole)){
			sql.append(" and company like '" + company + "%'");
		}
		List<Record> ruleList = Db.find(sql.toString());
		
		setAttr("ruleList", ruleList);
		render("pricerule_index.ftl");
	}
	
	public void edit() {
		setAttr("telPriceRule", TelPriceRule.dao.findById(getParaToInt()));
		render("pricerule_edit.ftl");
	}
	
	public void add() {
		render("pricerule_add.ftl");
	}
	
	public void setdefault(){
		int ruleId = getParaToInt();
		TelPriceRule telPriceRule = TelPriceRule.dao.findById(ruleId);
		
		String company = telPriceRule.getStr("company");
		Db.update("update tel_price_rule set is_default=0 where company=?",company);
		Db.update("update tel_price_rule set is_default=1 where id=?",ruleId);
		
		redirect("/pricerule");
	}
	
	public void save() {
		String name = getPara("telPriceRule.name");
		String company = getPara("telPriceRule.company");
		
		Db.update("insert into tel_price_rule(name,company) values(?,?)",name,company);
		
		redirect("/pricerule");
	}
	
	public void delete() {
		int id = getParaToInt();
		
		Db.update("delete from tel_price_rule where id=?",id);
		
		redirect("/pricerule");
	}
	
	public void update(){
		int id = getParaToInt("telPriceRule.id");
		String name = getPara("telPriceRule.name");
		String company = getPara("telPriceRule.company");
		
		Db.update("update tel_price_rule set name=?,company=? where id=?",name,company,id);
		redirect("/pricerule");
	}
}
